package com.zh.chat.dao.impl;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.zh.chat.dao.FriendsDAO;
import com.zh.chat.dao.UserDAO;
import com.zh.chat.entity.Friend;
import com.zh.chat.entity.Friends;
import com.zh.chat.entity.FriendsId;
import com.zh.chat.entity.User;
import com.zh.chat.file.FileManager;
import com.zh.chat.file.FileOperationUtil;

public class FriendsDAOImpl implements FriendsDAO {
	private Logger log = Logger.getLogger(FriendsDAOImpl.class);
	private Configuration config = new Configuration().configure();
	private SessionFactory factory = config.buildSessionFactory();
	private UserDAO udao = null;

	public FriendsDAOImpl() {
		log.info("FriendsServiceImpl初始化完成");
	}

	@Override
	public String addFriend(Long requestId, Long targetId, String dividedName) {
		Friends friend = new Friends();
		friend.setId(new FriendsId(requestId, targetId));
		friend.setDivideName(dividedName);
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		String msg = null;
		try {
			User user = udao.findById(targetId);
			if (user == null) {
				msg = "添加好友失败,用户不存在";
			} else {
				boolean flag = session.contains(friend);
				if (flag) {
					msg = "该好友关系已经存在";
				}
				friend = (Friends) session.save(friend);
				tx.commit();
				log.info(friend.getId().getSysId() + "添加好友"
						+ friend.getId().getFriendId() + "成功");
			}
		} catch (Exception e) {
			tx.rollback();
			log.error("添加好友失败" + e);
			e.printStackTrace();
		} finally {
			session.close();
		}
		return "好友添加成功";
	}

	@Override
	public String delFriend(Long requestId, Long targetId) {
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		Friends friend = null;
		try {
			friend = findFriendById(requestId, targetId);
			if (friend == null) {
				return "删除失败，没有这个好友关系";
			}
			session.delete(friend);
			tx.commit();
			log.info(friend.getId().getSysId() + "删除好友"
					+ friend.getId().getFriendId() + "成功");
		} catch (Exception e) {
			tx.rollback();
			log.error("添加好友失败" + e);
			e.printStackTrace();
		}
		return "好友删除成功";
	}

	@Override
	public Friends findFriendById(Long requestId, Long targetId) {
		Session session = factory.openSession();
		Friends friends = null;
		try {
			String hql = "from Friends where id.sysId=:sysId and id.friendId=:friendId";
			session.beginTransaction();
			Query query = session.createQuery(hql);
			query.setLong("sysId", requestId);
			query.setLong("friendId", targetId);
			List<Friends> list = query.list();
			if(list != null && list.size() == 1 ){
				friends = (Friends) list.get(0);
			}
		} catch (Exception e) {
			log.error(requestId + "查找好友" + targetId + "失败" + e);
			e.printStackTrace();
		}finally{
			session.close();
		}
		return friends;
	}

	@Override
	public List<Friend> getFriends(Long id) {
		Session session = factory.openSession();
		session.clear();
		String hql = "from Friends where id.sysId=?";
		Query query = session.createQuery(hql);
		query.setLong(0, id);
		List<Friends> list = query.list();
		if (list != null) {
			List<Friend> list2 = new ArrayList();
			for (Friends dbfriend : list) {
				list2.add(FriendsConvert(dbfriend));
			}
			session.close();
			return list2;
		}
		session.close();
		return null;
	}
	
	public void makeFriendsFile(Long id, int fileType, List<Friend> list){
		String json = getFriendsJson(list);
		String path = FileOperationUtil.getFilePath(fileType, id, "friendList.data");
		FileManager.newFile(path, json);
	}
	private String getFriendsJson(List<Friend> list){
		JSONArray json = new JSONArray();
		for (Friend f : list) {
			JSONObject jo = JSONObject.fromObject(f);
			json.add(jo);
		}
		return json.toString();
	}
	/**
	 * 将数据库中的懒惰加载的数据取出来
	 * @param friends
	 * @return
	 */
	private Friend FriendsConvert(Friends friends){
		Friend friend = new Friend();
		User user = friends.getUserByFriendId();
		friend.setFriendId(friends.getId().getFriendId());
		friend.setSysId(friends.getId().getSysId());
		friend.setUserPwd(user.getUserPwd());
		friend.setSex(user.getSex());
		friend.setStatus(user.getStatus());
		friend.setName(user.getName());
		friend.setNickname(user.getNickname());
		friend.setBirthday(user.getBirthday().getTime());
		friend.setRegisterDate(user.getRegisterDate().getTime());
		friend.setLastLoginDate(user.getLastLoginDate().getTime());
		friend.setImage(user.getImage());
		friend.setDivideName(friends.getDivideName());
		return friend;
	}

	@Override
	public String updateDivideName(java.lang.Long requestId,
			java.lang.Long targetId, String divideName) {
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		Friends friend = null;
		try {
			friend = findFriendById(requestId, targetId);
			if (friend == null) {
				return "该好友关系不存在";
			}
			friend.setDivideName(divideName);
			session.update(friend);
			log.info(friend.getId().getSysId() + "修改好友"
					+ friend.getId().getFriendId() + "分组"
					+ friend.getDivideName());
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			log.error("更新好友信息失败" + e);
			e.printStackTrace();
		} finally {
			session.close();
		}
		return "好友分组更新成功";
	}
}
